package cn.zhaoyan.filter;


import cn.zhaoyan.bean.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
@WebFilter(urlPatterns = "/*")
public class PrivilegeFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest)servletRequest;
        HttpServletResponse response= (HttpServletResponse)servletResponse;
        //获取用户请求路径
        String path = request.getRequestURI().substring(request.getContextPath().length());
        //公共资源的释放
        if("/login.jsp".equals(path)
           ||"/register.jsp".equals(path)
                ||"/hello.jsp".equals(path)
                ||"/CheckImgServlet".equals(path)
                ||"/FindServlet".equals(path)
                ||"/loginServlet".equals(path)
                ||"/RegisterServlet".equals(path)
                ||"/deful.jsp".equals(path)
                ||"/LoginOutServlet".equals(path)

        ){
            filterChain.doFilter(request,response);
            return;
        }
        //获取用户登录的信息
        User user =(User) request.getSession().getAttribute("ser1");
        if (user==null){
            response.sendRedirect(request.getContextPath()+"/login.jsp");
            return;
        }else {
            //判断是管理员还是普通用户
            if ("管理员".equals(user.getRole())){
                filterChain.doFilter(request,response);

            }else {
                if ("普通用户".equals(user.getRole())){
                    if ("/FindServlet".equals(path)){
                        filterChain.doFilter(request,response);
                        return;
                    }else {
                        request.getRequestDispatcher("/deful.jsp").forward(request,response);
                        return;
                    }
                }
            }
        }

    }

    @Override
    public void destroy() {

    }
}
